package rent.hj.videoplayer;

import android.content.Context;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Message;


import java.io.File;
import java.util.ArrayList;

import rent.hj.videoplayer.subTitle.SubTitleContent;


/**
 * Created by wangjianqiang on 2016/6/14.
 */
public class SubTitleHelper {
    private static final String TAG = "SubTitleHelper";
    private VideoPlayActivity mActivity = null;

    private boolean runSubtitleThread = false;
    public Thread subTitleShowThread = null;
    private boolean showSubTitleFlag = false;
    private MediaPlayer mMediaPlayer = null;
    private Context context;
    private Uri mUri;
    private int pos = 0;

    public boolean isRunSubtitleThread() {
        return runSubtitleThread;
    }

    public void finishDecode() {
        this.runSubtitleThread = false;
        if (subTitleShowThread != null) {
            subTitleShowThread.interrupt();
            subTitleShowThread = null;
        }
    }

    public void setshowSubTitleFlag(boolean showSubTitleFlag) {
        this.showSubTitleFlag = showSubTitleFlag;
    }

    public void init(VideoPlayActivity mActivity, String title) {
        this.mActivity = mActivity;
        context = mActivity;
        this.mTitle = title;
    }

    public void decodeSub(Uri mUri, MediaPlayer mMediaPlayer) {
        finishDecode();
        this.mMediaPlayer = mMediaPlayer;
        this.mUri = mUri;
        mActivity.subtitleList = null;
        new FileAsyncTask().execute();
    }

    public void decodeSub(String path, MediaPlayer mMediaPlayer) {
        finishDecode();
        this.mMediaPlayer = mMediaPlayer;
        mActivity.subtitleList = null;
        setSubTitlePath(path);
    }

    private void setSubTitlePath(final String subPath) {
        runSubtitleThread = true;
        if (subPath != null) {

            new Thread() {
                @Override
                public void run() {
                    SubContentUtil.stopDecodeFlag = false;
                    VideoPlayActivity.isShowingSubtitle = false;

                    mActivity.subtitleList = SubContentUtil.decodeSubtitle(subPath);

                    mActivity.decodeSubtitleFinish = true;
                }
            }.start();

            subTitleShowThread = new Thread() {
                int currPos = 0;

                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    SubTitleContent content = null;
                    SubTitleContent preContent = null;
                    Message msg = null;
                    int delayTime = 0;
                    showSubTitleFlag = true;

                    while (runSubtitleThread) {
                        if (mActivity == null) {
                            break;
                        }
                        if (mActivity.subtitleList == null || mActivity.subtitleList.size() == 0) {
                            try {
                                Thread.sleep(500L);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            continue;
                        }
                        if (!showSubTitleFlag) {
                            try {
                                Thread.sleep(500L);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            continue;
                        }
                        if (mMediaPlayer != null && showSubTitleFlag) {
                            currPos = mMediaPlayer.getCurrentPosition() + pos;
                            if (currPos < 0) {
                                currPos = 0;
                            }
                            content = SubContentUtil.getCurrentSubTitle(currPos, mActivity.subtitleList);
                            if (content != null) {
                                delayTime = content.getmSubTitleEndTime() - content.getmSubTitleStartTime();
                            }
                            if (!VideoPlayActivity.isShowingSubtitle) {
                                if (content != null) {
                                    if (subPath.endsWith(".idx")) {
                                        msg = new Message();
                                        msg.what = VideoPlayActivity.SHOW_IMGSUBTITLE;
                                        msg.obj = content.getmSubTitleBmp();
                                        clearAllMsg();
                                        mActivity.subtitleHandler.sendMessage(msg);
                                        if (content.getmSubTitleEndTime() == Integer.MAX_VALUE)
                                            mActivity.subtitleHandler.sendEmptyMessage(VideoPlayActivity.SHOW_LASTSUBTITLE);
                                        mActivity.subtitleHandler.sendEmptyMessageDelayed(VideoPlayActivity.HIDE_IMGSUBTITLE, delayTime);
                                    } else {
                                        msg = new Message();
                                        msg.what = VideoPlayActivity.SHOW_SUBTITLE;
                                        msg.obj = content.getmSubTitleLine();
                                        clearAllMsg();
                                        mActivity.subtitleHandler.sendMessage(msg);
                                        if (content.getmSubTitleEndTime() == Integer.MAX_VALUE)
                                            mActivity.subtitleHandler.sendEmptyMessage(VideoPlayActivity.SHOW_LASTSUBTITLE);
                                        mActivity.subtitleHandler.sendEmptyMessageDelayed(VideoPlayActivity.HIDE_SUBTITLE, delayTime);
                                    }
                                } else {
                                    clearAllMsg();
                                    mActivity.subtitleHandler.sendEmptyMessage(VideoPlayActivity.HIDE_SUBTITLE);
                                }

                                preContent = content;
                            } else {
                                if (preContent != null && content != null && preContent.getmSubTitleLine() != null && !preContent.getmSubTitleLine().equals(content.getmSubTitleLine())) {
                                    clearAllMsg();
                                    msg = new Message();
                                    msg.what = VideoPlayActivity.SHOW_SUBTITLE;
                                    msg.obj = content.getmSubTitleLine();
                                    mActivity.subtitleHandler.sendMessage(msg);
                                    if (content.getmSubTitleEndTime() == Integer.MAX_VALUE)
                                        mActivity.subtitleHandler.sendEmptyMessage(VideoPlayActivity.SHOW_LASTSUBTITLE);
                                    mActivity.subtitleHandler.sendEmptyMessageDelayed(VideoPlayActivity.HIDE_SUBTITLE, delayTime);

                                    preContent = content;
                                }
                            }
                            try {
                                Thread.sleep(500L);
                            } catch (InterruptedException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                        } else {
                            break;
                        }
                    }
                }
            };
            subTitleShowThread.start();
        }
    }

    private void clearAllMsg() {
        mActivity.subtitleHandler
                .removeMessages(VideoPlayActivity.HIDE_IMGSUBTITLE);
        mActivity.subtitleHandler
                .removeMessages(VideoPlayActivity.HIDE_SUBTITLE);
        mActivity.subtitleHandler
                .removeMessages(VideoPlayActivity.SHOW_SUBTITLE);
        mActivity.subtitleHandler
                .removeMessages(VideoPlayActivity.SHOW_LASTSUBTITLE);
        mActivity.subtitleHandler
                .removeMessages(VideoPlayActivity.SHOW_IMGSUBTITLE);
    }

    private class FileAsyncTask extends AsyncTask<Void, Void, String> {
        @Override
        protected String doInBackground(Void... params) {
            File file = new File(mUri.getPath());
            if (file.exists()) {
                try {
                    File parent = file.getParentFile();
                    String name = file.getName();
                    int index1 = name.lastIndexOf(".");
                    name = name.substring(0, index1);
                    File fileStr = new File(parent, name + ".str");
                        if (fileStr.exists()) {
                            return fileStr.getPath();
                        }
                        File fileAss = new File(parent, name + ".ass");
                        if (fileAss.exists()) {
                            return fileAss.getPath();
                        }
                        File fileSmi = new File(parent, name + ".smi");
                        if (fileSmi.exists()) {
                            return fileSmi.getPath();
                        }
                        File fileSsa = new File(parent, name + ".ssa");
                        if (fileSsa.exists()) {
                            return fileSsa.getPath();
                        }
                } catch (Exception e) {

                }

            }
            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            if (s != null) {
                setSubTitlePath(s);
            } else {
                mActivity.hideSubTitle();
            }
        }
    }
    String mTitle;
}
